package com.liangsui.mss.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * utils
 *
 * @author zhangjiawei
 * @email 1533167396@qq.com
 * @date 2022/12/2 17:22
 */
public class IdGeneratorSnowflake {
    private static final Logger log = LoggerFactory.getLogger(IdGeneratorSnowflake.class);
    private static long workId = 0;
    private static long datacenterId = 1;
    private static Snowflake snowflake;

    static {
        try {
            workId = RandomUtil.randomLong(31);
            log.info("当前机器的工作ID为:" + workId);
            snowflake = IdUtil.createSnowflake(workId, datacenterId);
            log.info("snowflake" + snowflake);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("当前机器的workId获取失败", e);
            workId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    /**
     * 生成6位验证密码
     */
    public static Integer generateVerificationCode() {
        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 100000;
        return randomNumber;
    }

    /**
     * 生成ID
     */
    public static synchronized Long snowflakeId() {
        log.info("snowFlake:" + snowflake);
        return snowflake.nextId();
    }

    /**
     * 根据前缀前成ID
     */
    public static String generatorIdWithProfix(String profix) {
        return profix + snowflakeId();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Long aLong = IdGeneratorSnowflake.snowflakeId();
            System.out.println(aLong);
        }
    }
}
